import React, { use, useEffect, useState } from 'react';
import { Pagination, WhiteSpace, WingBlank } from '@ant-design/react-native'
import { ScrollView, View, Text} from 'react-native';
import DeviceCard from '@/components/features/device/DeviceCard';
import SearchBar from '@/components/features/device/SearchBar';
import ButtonDemo from '@/components/features/device/ButtonDemo';
import UserCard from '@/components/features/device/UserCard';
import { CurrentSceneCard } from '@/components/features/device/CurrentSceneCard';

import Scene from '@/components/features/device/Scene';
import { HomePageCard } from '@/components/features/device/HomePageCard';
import { router, useFocusEffect } from 'expo-router';
import { registerUser, loginUser, logoutUser, refreshToken, getUserProfile } from '../../api/auth';
import { getDevices, createDevice, getDeviceDetails, deleteDevice, updateDeviceState, getDeviceStateHistory } from '../../api/device';
import { getScenes, createScene, getSceneDetails, updateScene, deleteScene,
    removeSceneDevice, adjustScenePriority, activateScene, getActiveScenes, switchScene } from '../../api/scene';
import getDeviceImage from '@/api/getDeviceImage';
import { getDisplayValueFromState } from '@/api/deviceStateMap';

interface DeviceData {
    id: number;
    name: string;
    type: string;
    family: string;
    meta?: Record<string, any>;
    state?: Record<string, any>;    
}

interface SceneData {
    id: number;
    name: string;
    priority?: number;
    enabled?: boolean;
}

const deviceCategories = {
    security: ['smart_lock_with_cat_eye', 'smoke_co_alarm', 'motion_sensor', 'camera'],
    lighting: ['light'],
    homeAppliances: [
        'air_conditioner',
        'humidifier',
        'air_purifier',
        'refrigerator',
        'washing_machine',
        'dishwasher',
        'water_heater',
        'exhaust_fan',
        'smart_tv'
    ],
    cleaning: ['vacuum_robot'],
    shading: ['curtain'],
    environmentalMonitoring: ['temp_humidity_sensor'],
    audio: ['smart_speaker'],
    // default: ['camera']
};

function renderCategorizedDeviceList(deviceList: DeviceData[]) {
    const categorizedDevices: Record<string, DeviceData[]> = {};

    // 初始化分类
    Object.keys(deviceCategories).forEach(category => {
        categorizedDevices[category] = [];
    });

    // 按照设备类型归类
    deviceList.forEach(device => {
        let foundCategory = 'default';

        // 查找该设备属于哪个分类
        for (const [category, types] of Object.entries(deviceCategories)) {
            if (types.includes(device.type)) {
                foundCategory = category;
                break;
            }
        }

        categorizedDevices[foundCategory].push(device);
    });

    // const handleSceneSelect = async (scene: SceneData) => {
    //     try {
    //         // 先激活该场景（关闭其它场景）
    //         await switchScene(scene.id);

    //         // 再获取场景详情和设备
    //         const response = await getSceneDetails(scene.id);
    //         if (response.data.ok && response.data.data) {
    //             const sceneDetails = response.data.data;
    //             const actionDeviceIds = sceneDetails.actions?.map((a: any) => a.device_id) || [];
    //             const devicesInScene = deviceList.filter(device =>
    //                 actionDeviceIds.includes(device.id)
    //             );
    //             // setCurrentScene(sceneDetails);
    //             setSceneDevices(devicesInScene);
    //             // 刷新场景列表，确保其它场景状态更新
    //             fetchSceneList();
    //         } else {
    //             alert('错误，无法加载场景详情');
    //         }
    //     } catch (error) {
    //         console.error('切换场景失败:', error);
    //         alert('错误，切换场景失败');
    //     }
    // };

    return (
        <View>
            {Object.entries(categorizedDevices).map(([category, devices]) => {
                if (devices.length === 0) return null;

                return (
                    <View key={category} style={{ width: 330, marginTop: 24 }}>
                        <Text style={{ fontSize: 24, fontWeight: 'bold', marginBottom: 12 }}>
                            {translateCategory(category)}
                        </Text>
                        <WhiteSpace size="lg" />
                        {Array.from({ length: Math.ceil(devices.length / 2) }).map((_, rowIdx) => (
                            <View
                                key={rowIdx}
                                style={{
                                    flexDirection: 'row',
                                    justifyContent: 'space-between',
                                    marginBottom: 12,
                                }}
                            >
                                {devices.slice(rowIdx * 2, rowIdx * 2 + 2).map(device => (
                                    <View key={device.id} style={{ width: '48%', marginBottom: 8 }}>
                                        <DeviceCard
                                            image={getDeviceImage(device.type)}
                                            title={device.name}
                                            desc={getDisplayValueFromState(device.state ?? {}) ?? '已停止'}
                                        />
                                    </View>
                                ))}
                            </View>
                        ))}
                    </View>
                );
            })}
        </View>
    );
}

function translateCategory(category: string): string {
    const translations: Record<string, string> = {
        security: '安防设备',
        lighting: '照明设备',
        homeAppliances: '家电设备',
        cleaning: '清洁设备',
        shading: '遮挡控制设备',
        environmentalMonitoring: '环境监测设备',
        audio: '音频设备',
        default: '默认设备'
    };
    return translations[category] || category;
}

const sceneImages = {
    1: require('../../assets/sceneImages/1.png'),
    2: require('../../assets/sceneImages/2.png'),
    3: require('../../assets/sceneImages/3.png'),
    4: require('../../assets/sceneImages/4.png'),
    5: require('../../assets/sceneImages/5.png'),
    6: require('../../assets/sceneImages/6.png'),
    7: require('../../assets/sceneImages/7.png'),
    8: require('../../assets/sceneImages/8.png'),
    9: require('../../assets/sceneImages/9.png'),
    default: require('../../assets/sceneImages/9.png'),
};

const renderActiveScenes = (list: SceneData[]) => {
    if (!list || list.length === 0) return null;

    return list.map((scene) => {
        const imageIndex = scene.id % 9 + 1;
        const image = sceneImages[imageIndex as keyof typeof sceneImages] || sceneImages.default;

        return (
            <View key={scene.id} style={{ marginBottom: 16 }}>
                <HomePageCard
                    image={image}
                    title={scene.name}
                    desc={`已开启`}
                    onAddPress={() => router.push(`/ScenePage`)}
                    buttonText='查看'
                />
            </View>
        );
    });
};

export default function BlankScreen() {
    const [deviceList, setDeviceList] = useState<DeviceData[]>([]);
    const [sceneList, setSceneList] = useState<SceneData[]>([]);
    const activeScenes = sceneList.filter(scene => scene.enabled === true);
    // const 
    const [profile, setProfile] = useState({
        username: '',
        avatar_url: '',
        nickname: '',
    });

    useEffect(() => {
        fetchUserProfile();
        fetchDeviceList();
        fetchSceneList();
    }, []);

    useFocusEffect(
        React.useCallback(() => {
            fetchUserProfile();
            fetchDeviceList();
            fetchSceneList();
        }, [])
    );

    const fetchSceneList = async () => { 
        try {
            const response = await getScenes();
            const sceneList = response.data.data.scenes;
            setSceneList(sceneList);
            setSceneList(Array.isArray(sceneList) ? sceneList : []);
        } catch (error) { 
            console.error('Get scenes error:', error);
        }
    };

    const fetchUserProfile = async () => {
        try {
            const response = await getUserProfile();
            setProfile({
                username: response.data.username || '',
                avatar_url: response.data.avatar_url || '',
                nickname: response.data.nickname || '',
            });
            console.log('获取用户信息成功:', response.data);
        } catch (error) {
            console.error('获取用户信息失败:', error);
        }
    };

    const fetchDeviceList = async () => { 
        try {
            const response = await getDevices();
            const deviceList = response.data.data.devices;
            setDeviceList(deviceList);
            setDeviceList(Array.isArray(deviceList) ? deviceList : []);
        } catch (error) { 
            console.error('Get devices error:', error);
        }
    }; 

    // 获取一个未开启的场景
    const inactiveScene = sceneList.find(scene => scene.enabled === false);

    return (
        <View style={{ flex: 1 }}>
            <ScrollView style={{ flex: 1, backgroundColor: '#fff' }}>
                <View style={{ alignItems: 'center', marginLeft: 20, marginRight: 20, borderRadius: 100 }}>
                    <View style={{ width: 330, alignSelf: 'center', marginTop: 60 }}>
                        <UserCard
                            avatar={profile.avatar_url}
                            username={profile.username || '' }
                            nickname={profile.nickname || ''}
                            // onEditPress={() => alert('点击修改用户信息')}
                        />
                    </View>
                    {/* <ButtonDemo
                        text="返回index（测试用）"
                        onPress={() => router.replace('/')}
                    /> */}
                    <View style={{ width: 330, alignSelf: 'center' }}>
                        <Text
                            style={{
                                fontSize: 24,
                                fontWeight: 'bold',
                                marginBottom: 8,
                            }}
                        >
                            当前使用的场景
                        </Text>
                    </View>
                    <WhiteSpace size="lg" />
                    {renderActiveScenes(activeScenes)}
                    <WhiteSpace size='lg' />
                    <WhiteSpace size='lg' />
                    <View style={{ width: 330, alignSelf: 'center' }}>
                        <Text
                            style={{
                                fontSize: 24,
                                fontWeight: 'bold',
                                marginBottom: 8,
                            }}
                        >
                            场景推荐
                        </Text>
                    </View>
                    <WhiteSpace size='lg' />
                    {inactiveScene ? (
                        <HomePageCard
                            image={sceneImages[(inactiveScene.id % 9 + 1) as keyof typeof sceneImages] || sceneImages.default}
                            title={inactiveScene.name}
                            desc="未开启"
                            onAddPress={async () => {
                                await switchScene(inactiveScene.id);
                                router.push({ pathname: '/ScenePage', params: { sceneId: inactiveScene.id } });
                            }}
                            buttonText='使用'
                        />
                    ) : (
                        <HomePageCard
                            image={require('../../assets/images/Scene.jpg')}
                            title="暂无可用推荐场景"
                            desc="暂无未开启场景"
                            onAddPress={() => alert('暂无未开启场景')}
                            buttonText='使用'
                        />
                    )}
                </View>
                <View style={{ alignItems: 'center', marginTop: 32, marginBottom: 32 }}>
                    {renderCategorizedDeviceList(deviceList)}
                </View>
                <WhiteSpace size='lg'/>
                <WhiteSpace size='lg'/>
                <WhiteSpace size='lg'/>
                <WhiteSpace size='lg'/>
            </ScrollView>
        </View>
    );
}